/*
 * Powered By xTOOLs
 * Dev by DuRisk@pactera.com
 * Copyright © 2009 - 2017 pactera.com. All rights reserved.
 *
 * Generated at 2017年11月20日 16:16:48
 *
 */

package com.pactera.jep.service.sys.web.controller;

import com.pactera.jep.core.code.YesNo;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.dash.provider.DataProvider;
import com.pactera.jep.sys.dash.provider.DataProviderFactory;
import com.pactera.jep.sys.dash.provider.spring.SpringDataProviderFactoryBean;
import com.pactera.jep.sys.dash.widget.utils.mvel.MVELUtils;
import com.pactera.jep.sys.model.DashWidgetProvider;
import com.pactera.jep.sys.service.DashWidgetProviderService;
import com.pactera.jep.sys.service.DashWidgetService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.controller.CrudController;
import com.pactera.jep.web.entity.NameValuePair;
import com.pactera.jep.web.util.NVUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("绑定数据源")
@RestController
@RequestMapping("/dashWidgetProvider")
public class DashWidgetProviderRestController extends CrudController<DashWidgetProvider> {
	private static Logger	logger	= LoggerFactory.getLogger(DashWidgetProviderRestController.class);

	@Autowired
	private DashWidgetProviderService dashWidgetProviderService;
	
	@Autowired
	private DashWidgetService dashWidgetService;//组件的service

	@Autowired
	private SpringDataProviderFactoryBean factoryBean;
	

	
	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(Page<DashWidgetProvider> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {
		
		dashWidgetProviderService.query(page, filters, orders);
	}
	

	
	/**
	 * 保存
	 * @param dashWidgetProvider
	 * @return
	 */
	@ApiOperation("保存")
	@PostMapping(value = "/save")
	public Map<String, Object> save(@RequestBody DashWidgetProvider dashWidgetProvider) {
		
		//公用字段统一处理
//		UserProfile userProfile = UserProfileUtils.getUserProfile();
//		dashWidgetProvider.setCreateById(userProfile.getUserid());
//		dashWidgetProvider.setCreateByName(userProfile.getStaffName());
//		dashWidgetProvider.setCreateTime(new Date());
//		dashWidgetProvider.setDelflag("N");
		
		Map<String, Object> tips = new HashMap<String, Object>();
		Boolean isExist = dashWidgetProviderService.exists(dashWidgetProvider.getProvierId());
		try 
		{
			if(isExist)
			{
				
				dashWidgetProviderService.update(dashWidgetProvider);
			}
			else
			{
				dashWidgetProvider.setBeenUsed(YesNo.NO.getValue());
				dashWidgetProviderService.insert(dashWidgetProvider);
			}
			
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (ServiceException e)
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}
	
	/**
	 * 删除
	 * @param provierId
	 * @return
	 */
	@ApiOperation("删除")
	@PostMapping(value = "/remove/{provierId}")
	public Map<String, Object> remove(@PathVariable String provierId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		try 
		{
			int i=dashWidgetProviderService.deleteByPrimaryKey(provierId);
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
		} 
		catch (ServiceException e)
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
		}
		
		return tips;
	}
	
	/**
	 * 验证提交的provierId是否已经存在数据库中
	 * @param provierId
	 * @return
	 */
	@ApiOperation("验证提交的provierId是否已经存在数据库中")
	@PostMapping(value = "/check", produces = "application/json;charset=UTF-8")
	public Map<String, Object> check(String provierId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		boolean exist = dashWidgetProviderService.exists(provierId);
		tips.put("valid", !exist);
		
		return tips;
	}
	

	/**
	 * 验证组件是否绑定数据程序
	 * @param widgetCode
	 * @return
	 */
	@ApiOperation("验证组件是否绑定数据程序")
	@GetMapping(value = "/verifyForDashWidgetProvider/{widgetCode}")
	public Map<String, Object> verifyForDashWidgetProvider(@PathVariable String widgetCode){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		long count = dashWidgetProviderService.count(new Filter.Builder().eq("widgetCode", widgetCode).build());
		if(count > 0)
		{
			tips.put(WebCode.SUCCESS, true);
		}
		else
		{
			tips.put(WebCode.SUCCESS, false);
		}
		
		return tips;
	}
	
	/**
	 * 获得组件的列数据
	 * @param widgetProvierId
	 * @return
	 */
	@ApiOperation("获得组件的列数据")
	@SuppressWarnings("rawtypes")
	@GetMapping(value="/getDataProviderByWidgetProvierId/{widgetProvierId}")
	public Map<String,Object> getDataProviderByWidgetProvierId(@PathVariable String widgetProvierId){
		Map<String,Object> data = new HashMap<String,Object>();
		DashWidgetProvider dashWidgetProvider = dashWidgetProviderService.get(widgetProvierId);
		Page page = new Page(1, 10);
		
		try 
		{
			DataProviderFactory dataProviderFactory = factoryBean.getObject();
			DataProvider provider = dataProviderFactory.createDataProvider(dashWidgetProvider.getProviderCode(), page,
					dashWidgetProvider.getProviderParams(), null);
			data.put("columns", provider.getDescriptor().getColumns());
			data.put("name", provider.getName());
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return data;
	}
	
	/**
	 * 验证表达式结果 
	 * @param expr
	 * @param widgetProvierId
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/verifyExpr")
	public Map<String,Object> verifyExpr(String expr,String widgetProvierId){
		Map<String, Object> data = new HashMap<String, Object>();
		DashWidgetProvider dashWidgetProvider = dashWidgetProviderService.get(widgetProvierId);
		Page page = new Page(1, 10);
		
//		DataProvider3 dataProvider = DataProviderFactory2.createDataProvider(provider.getProviderCode(), 
//				provider.getProviderParams(),DataProvider3.MODE_DESIGN, page,PermitType.UNIT_ALL);
		
		DataProvider provider = null;
		try 
		{
			DataProviderFactory dataProviderFactory = factoryBean.getObject();
			provider = dataProviderFactory.createDataProvider(dashWidgetProvider.getProviderCode(), page, 
					dashWidgetProvider.getProviderParams(), null);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		List<Map<String, Object>> dataRows = provider.getData();
		Map<String, Object> params = new HashMap<String, Object>();
		
		/*如果数据不为空的话，就直接取出第一条数据*/
		if(!CollectionUtils.isEmpty(dataRows))
		{
			params.put("dataRow", dataRows.get(0));
		}
		
		try 
		{
			MVELUtils.eval(expr, params);
			data.put(WebCode.SUCCESS,true);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			logger.info(e.getMessage());
			data.put(WebCode.SUCCESS,false);
		}
		return data;
	}
	
	/**
	 * 根据组件编码，获取该组件的数据提供程序
	 * @param widgetCode
	 * @return
	 */
	@ApiOperation("根据组件编码，获取该组件的数据提供程序")
	@GetMapping("/getWidgetProvidersByWidgetCode")
	public List<NameValuePair> getWidgetProvidersByWidgetCode(String widgetCode){
		DashWidgetProvider widgetProvider=new DashWidgetProvider();
		widgetProvider.setWidgetCode(widgetCode);
		List<DashWidgetProvider> list = dashWidgetProviderService.select(widgetProvider);
		return NVUtils.convert(list, list.size(), "provierId", "providerName");
	}
	
	
	
	
	
}